package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.entity.DmDmContractDay;
import cn.com.cifi.mars.entity.DmDmContractMonth;
import cn.com.cifi.mars.entity.VDmDmContractDay;
import cn.com.cifi.mars.entity.VDmDmContractMonth;
import cn.com.cifi.mars.mapper.mars.DmDmContractMonthMapper;
import cn.com.cifi.mars.service.DmDmContractMonthService;
import cn.com.cifi.mars.service.VDmDmContractDayService;
import cn.com.cifi.mars.service.VDmDmContractMonthService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author plx
 * @since 2019-12-17
 */
@Service
public class DmDmContractMonthServiceImpl extends ServiceImpl<DmDmContractMonthMapper, DmDmContractMonth> implements DmDmContractMonthService {

    private static final Logger logger = LoggerFactory.getLogger(DmDmContractMonthServiceImpl.class);

    @Autowired
    private VDmDmContractMonthService vDmDmContractMonthService;



    @Override
    public void sync() {
        //清空
        remove(new QueryWrapper<>());
        logger.info("清空DmDmContractMonth数据完毕");

        //同步
        int pageNo = 0;
        int pageSize = 3000;
        Page<VDmDmContractMonth> page = new Page<>(pageNo, pageSize);
        logger.info("同步DmDmContractMonth数据开始");
        do {
            page.setCurrent(++pageNo);
            vDmDmContractMonthService.page(page);
            logger.info("总数：{}，总批次：{}，当前批次：{}，每批数量：{},本批数量：{}", page.getTotal(), page.getPages(), page.getCurrent(), page.getSize(), page.getRecords().size());
            if (!page.getRecords().isEmpty()) {
                List<DmDmContractMonth> list = page.getRecords().parallelStream()
                        .map(x -> {
                            DmDmContractMonth dest = new DmDmContractMonth();
                            try {
                                PropertyUtils.copyProperties(dest, x);
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                            return dest;
                        }).collect(Collectors.toList());
                saveBatch(list);
            }
        } while (page.hasNext());
        logger.info("同步DmDmContractMonth数据结束");
    }

    @Override
    public void syncV2() {
        //清空
        remove(new QueryWrapper<>());
        logger.info("清空DmDmContractMonth数据完毕");

        //同步
        logger.info("同步DmDmContractMonth数据开始");
        baseMapper.insertSync();
        logger.info("同步DmDmContractMonth数据结束");
    }

    @Override
    public void syncV3(long batchSize) {
        //清空
        remove(new QueryWrapper<>());
        logger.info("清空DmDmContractMonth数据完毕");

        //同步
        long pageNo = 0;
        long pageSize = batchSize;
        Page<VDmDmContractMonth> page = new Page<>(pageNo, pageSize);
        logger.info("同步DmDmContractMonth数据开始");
        do {
            page.setCurrent(++pageNo);
            vDmDmContractMonthService.page(page);
            logger.info("总数：{}，总批次：{}，当前批次：{}，每批数量：{},本批数量：{}", page.getTotal(), page.getPages(), page.getCurrent(), page.getSize(), page.getRecords().size());
            if (!page.getRecords().isEmpty()) {
                List<DmDmContractMonth> list = page.getRecords().parallelStream()
                        .map(x -> {
                            DmDmContractMonth dest = new DmDmContractMonth();
                            try {
                                PropertyUtils.copyProperties(dest, x);
                            } catch (Exception e) {
                                logger.error(e.getMessage(), e);
                            }
                            return dest;
                        }).collect(Collectors.toList());
                saveBatch(list);
            }
        } while (page.hasNext());
        logger.info("同步DmDmContractMonth数据结束");
    }

    @Override
    public List<Map<String, Object>> listSum(LocalDate endDate) {
        QueryWrapper<DmDmContractMonth> signWrapper = new QueryWrapper<>();
        List<String> signSelecte = new ArrayList<>();
        String sumSign = "sum(case when %s then ifnull(%s,0) else 0 end) AS %s";
        String signHistory = "d_year < " + endDate.getYear();
        String signCurrent = "d_year = " + endDate.getYear() + " and d_month = %s";
        signSelecte.add("BldPrdId");
        signSelecte.add(String.format(sumSign, signHistory, "ts", "history_ts"));
        signSelecte.add(String.format(sumSign, signHistory, "je", "history_je"));
        signSelecte.add(String.format(sumSign, signHistory, "mj", "history_mj"));
        for (int i = 1; i <= endDate.getMonthValue(); i++) {
            String condition = String.format(signCurrent, i);
            signSelecte.add(String.format(sumSign, condition, "ts", i + "_ts"));
            signSelecte.add(String.format(sumSign, condition, "je", i + "_je"));
            signSelecte.add(String.format(sumSign, condition, "mj", i + "_mj"));
        }
        signWrapper.select(signSelecte.toArray(new String[]{}));
        signWrapper.groupBy("BldPrdId");
        return listMaps(signWrapper);
    }
}
